<script>
import {defineComponent} from 'vue'
import {delJaEvent, delJAn, getJAn} from "@/api/api";
import {Message} from "element-ui";
import { EventBus } from "@/tools/bus";
import { wsSend } from "@/tools/sendMessage";

export default defineComponent({
    name: "loadJiaoAn",
    data() {
        return {
            loading:null,
            ws:null,
            dialogVisible: true, // 控制弹窗显示
            currentJiaoAnId: null,
            currentJiaoAn: {
                teaDesc:'',
                gkName:'',
                name:'',
                id:'',
                gkId:'',
            },
            jiaoAnList: [],
            localLoadJiaoAn: this.loadJiaoAn,
            jiaoAn:'',
            form: {
                description: "",
                file: "",
                event: "",
            },
            tableData: [
            ],
            selectedRows:[]

        };
    },
    props:{
        loadJiaoAn:{
            type:Boolean,
            default:false
        }
    },
    watch: {
        // 监听父组件的 prop 变化并同步到本地副本
        loadJiaoAn(newVal) {
            this.currentJiaoAnId = null;
            this.currentJiaoAn= {
                teaDesc:'',
                gkName:'',
                name:'',
                id:'',
                gkId:'',
            };
            this.localLoadJiaoAn = newVal;
            if (newVal){
                this.getJAList()
            }
        }
    },
    mounted() {
      EventBus.$on('ws-message', (data) => {
        if (data.cmd === 'loadTeach') {
            this.loading.close();
            this.$message.success('加载成功')
        }
      });
    },
    beforeDestroy() {
        EventBus.$off('ws-message');
    },
  methods:{
        close(){
           this.$emit('DialogClose')
        },
       async removeEvent(){
            if (!this.selectedRows.length) {
                this.$message.warning('请先选择要删除的项');
                return;
            }

            try {
                const promises = this.selectedRows.map(id => delJaEvent({ id }));
                const results = await Promise.allSettled(promises);
                const successCount = results.filter(result => result.status === 'fulfilled' && result.value?.data?.code === 200).length;
                const errorCount = results.length - successCount;

                if (successCount === results.length) {
                    this.$message.success('全部删除成功');
                } else if (errorCount === results.length) {
                    this.$message.error('全部删除失败，请检查网络设置');
                } else {
                    this.$message.info(`部分删除成功，成功 ${successCount} 项，失败 ${errorCount} 项`);
                }
                await this.getJAList();
                this.selectedRows=[];
                this.setCurrentJA();
            } catch (error) {
                this.$message.error(`删除时发生错误：${error.message}`);
            }
        },
        handleSelectionChange(val) {
            this.selectedRows = [];
            if (val){
                val.forEach(item=>{
                    this.selectedRows.push(item.id)
                })
            }
        },
        setCurrentJA(){
          this.jiaoAnList.find(item=>{
              if (item.id===this.currentJiaoAnId){
                  this.currentJiaoAn=item
              }
          })
        },
        async getJAList(){
            const res= await getJAn();
            if (res.data.code===200){
                this.jiaoAnList=res.data.data
                console.log(this.jiaoAnList)
            }else{
                this.$message.error('获取教案失败,请检查网络设置')
            }
        },
      async delJA(){
            if (this.currentJiaoAnId){
                this.$refs.delBtn.disabled=true
                const res= await delJAn({id:this.currentJiaoAnId})
                if (res.data.code===200){
                    this.$message.success('删除成功');
                    await this.getJAList();
                    this.currentJiaoAnId=null
                    this.currentJiaoAn= {
                        teaDesc:'',
                        gkName:'',
                        name:'',
                        id:'',
                        gkId:'',
                    }
                    this.$refs.delBtn.disabled=false
                }else{
                    this.$message.error('删除失败,请检查网络设置')
                }
            }else{
                this.$message.error('请选择教案')
            }

      },
        loadJA(){
            if (!this.currentJiaoAnId){
                this.$message.error('请选择教案')
                return
            }
            this.loading=Message({
                message: '加载中......',
                duration: 0,
                type: 'info',
            })
            const params={
                "cmd":"loadTeach",
                "id":this.currentJiaoAnId
            }
            console.log(params,'loadJAInformation')
            wsSend(params)
        },
    }
})
</script>

<template>
    <el-dialog title="教案选择" :visible.sync="localLoadJiaoAn" width="90rem" @close="close" custom-class="switchPatrolDialog"  >
       <div class="main">

        <div style="width: 27%;">
            <span>当前教案：<b>{{currentJiaoAn.name}}</b></span>
           <br>
            <div class="jiaoanList">
           <span>教案列表</span>
           <div style="overflow: scroll" class="listbox">
               <el-radio-group v-model="currentJiaoAnId" style="display: flex;flex-direction: column" @change="setCurrentJA" >
                   <el-radio v-for="(item,index) in jiaoAnList" :key="index" :label="item.id"  style="margin: .4rem 0">{{item.name}}</el-radio>
               </el-radio-group>
           </div>
                <div class="btn">
                    <el-button type="primary" @click="loadJA">加载</el-button>
                    <el-button type="primary" @click="delJA" ref="delBtn" v-permission="['admin','teacher']">删除</el-button>
                    <el-button type="primary" @click="close">取消</el-button>
                </div>
            </div>
       </div>
           <fieldset style="width: 71%;border: 1px solid #666; border-radius: 5px;padding: 2rem;box-sizing: border-box">
               <legend>教案属性</legend>
               <div>
              <span>描述:</span>
               <el-input style="width: 48rem;margin-left: 1rem;" v-model="currentJiaoAn.teaDesc" disabled></el-input>
               </div>
               <div style="margin-top: 1rem">
               <span style="margin-right: 4.5rem">事件：</span>
               <span>工况文件:</span>
               <el-input style="width: 38rem;margin-left: 1rem;" v-model="currentJiaoAn.gkName" disabled></el-input>    </div>
               <div class="eventList">
                   <el-table :data="currentJiaoAn.events" v-model="selectedRows" @selection-change="handleSelectionChange"  height="200">
                       <el-table-column type="selection" width="55"></el-table-column>
                       <el-table-column label="序号" width="60" prop="id" align="center" header-align="center" >
                       </el-table-column>
                       <el-table-column label="间隔名称" width="140" prop="jgName" align="center" header-align="center">
                       </el-table-column>
                       <el-table-column label="设备名称" width="140" prop="devName" align="center" header-align="center">
                       </el-table-column>
                       <el-table-column label="事件描述" width="530" prop="eventDesc" align="center">
                       </el-table-column>
                   </el-table>
               </div>
               <div style="display: flex;margin-top: 10px">
               <el-button type="primary" style="margin-left: auto" @click="removeEvent" v-permission="['admin','teacher']">删除事件</el-button>
               </div>
           </fieldset>
       </div>
<!--       </div>-->
    </el-dialog>
</template>

<style scoped lang="less">
.el-button{
    color: #ebeff0;
    background: linear-gradient(#176575,#07283f);
    border:0;
    box-shadow: 0 -2px 0 rgba(16, 164, 195, .8);
    width: 8rem;
}
.main{
    display: flex;
    flex-direction: row;
  justify-content: space-between;
}
span,fieldset{
    color: white;
    font-size: 1.1rem;
}

.jiaoanList{
    margin-top: 1rem;
    padding-left: 1rem;
}
.listbox{
    border: 1px solid #666;
    border-radius: 5px;
    margin: .5rem 0;
    padding-left: .5rem;
    height: 23rem;
}
.btn{
    display: flex;
    flex-direction: row;
    justify-content: space-between;
}
.rightMain{


}

:deep(.el-input__inner) {
  background-color: transparent;
  border-color: rgba(255, 255, 255, 0.2);
  color: #fff;
}
:deep(.is-disabled .el-input__inner){
  background-color: #131f2a;
  border-color: rgba(255, 255, 255, 0.2);
  color: #999;
}
.eventList{
  margin-top: 1rem;
  background-color: transparent !important;
  height: 15rem;
  overflow: hidden;
  border-bottom: 1px solid #999;
}


/* 自定义 el-table 列单元格背景为透明 */
/deep/ .el-table .el-table__body tr {
  background-color: transparent !important; /* 设置行的背景为透明 */
}


/* 修改单元格边框颜色为透明 */
/deep/ .el-table th, .el-table td {
  border-color: #999 !important;
}
/deep/ .el-table th.el-table__cell{
  background-color: rgb(2, 22, 42) !important;
  color: #fff !important;
  font-weight: 700;
}


</style>
